<template>
    <el-upload :http-request="upload" ref="uploadRef" :limit="1" :on-exceed="handleExceed"
        :before-upload="beforeAvatarUpload" :show-file-list="false" accept=".jpg,.png" class="x-uploader" drag>
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
            <Plus />
        </el-icon>
        <div class="el-upload__text">
            拖动图片到这儿或 <em>点击上传</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                只支持不大于 2mb 的 jpg/png 文件
            </div>
        </template>
    </el-upload>
</template>
  
<script setup lang="ts">
import { genFileId, UploadInstance, UploadProps, UploadRawFile, UploadRequestOptions } from 'element-plus';
import * as Message from '../utils/message-utils'

const props = defineProps({
    result: Function,
    currentImg: String
})

const imageUrl = ref('')
const uploadRef = ref<UploadInstance>()

onMounted(() => {
    imageUrl.value = props.currentImg!
})

onBeforeUpdate(() => {
    imageUrl.value = props.currentImg!
})

const refreshImage = (file: File) => {
    const reader = new FileReader();
    reader.readAsDataURL(file)
    reader.onloadend = ({ target }) => {
        //@ts-ignore
        imageUrl.value = target!.result
        //@ts-ignore
        props.result(target!.result)
    }
}

const upload = (request: UploadRequestOptions) => {
    refreshImage(request.file)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        Message.error('图片必须是 JPG 或 PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        Message.error('图片尺寸不能大于 2MB!')
        return false
    }
    return true
}

const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
    refreshImage(file)
}

</script>

<style scoped>
.avatar {
    width: 128px;
    height: 128px;
}
</style>